package com.qfx.demo.shiro;

import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.qfx.demo.cache.MenuRoleCache;
import com.qfx.demo.cache.MenuRoleCache2;
import com.qfx.demo.vo.SysMenuRole;

@Component
public class ShiroPermissionSer {

	@Autowired
	ShiroFilterFactoryBean shiroFilterFactoryBean;

	private int count = 1;

	/**
	 * <h5>功能:动态更新shiro权限(无需重启)</h5>
	 * 
	 * @return 
	 */
	public boolean updatePermission() {
		boolean flag = false;
		synchronized (shiroFilterFactoryBean) {
			AbstractShiroFilter shiroFilter = null;
			try {
				shiroFilter = (AbstractShiroFilter) shiroFilterFactoryBean.getObject();
				PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
				DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();
				// 1. 清空老的权限控制
				manager.getFilterChains().clear();
				shiroFilterFactoryBean.getFilterChainDefinitionMap().clear();
				
				// ========== 2. 动态加载权限核心部分开始 ==========
				// 后面这个可以直接从数据库里面获取
		        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
		        // 对静态资源设置匿名访问,从resoutces/static后面开始写
		        filterChainDefinitionMap.put("/css/**", "anon");
		        // 可匿名访问的地址
		        filterChainDefinitionMap.put("/", "anon");
		        filterChainDefinitionMap.put("/index.jsp", "anon");
		        filterChainDefinitionMap.put("/login/loginPage", "anon");
		        filterChainDefinitionMap.put("/login/register", "anon");
		        filterChainDefinitionMap.put("/login/login", "anon");
		        // 请求 logout.do地址,shiro去清除session
		        filterChainDefinitionMap.put("/logout", "logout");
		        
		        //循环url,逐个添加到section中。section就是filterChainDefinitionMap,
		        //里面的键就是链接URL,值就是存在什么条件才能访问该链接(正式环境从数据库获取,这里模拟数据权限切换)
		        if (count == 1) {
		        	Map<String, SysMenuRole> menuRoleMap = MenuRoleCache2.menuRoleCacheMap;
		        	for (String key : menuRoleMap.keySet()) {
		        		filterChainDefinitionMap.put(key, "jwt, roles["+menuRoleMap.get(key).getRoleNames()+"]");
		        	}
		        	count = 0;
				} else {
					Map<String, SysMenuRole> menuRoleMap = MenuRoleCache.menuRoleCacheMap;
		        	for (String key : menuRoleMap.keySet()) {
		        		filterChainDefinitionMap.put(key, "jwt, roles["+menuRoleMap.get(key).getRoleNames()+"]");
		        	}
		        	count = 1;
				}
		        
		        //所有url都必须认证通过才可以访问，必须放在最后
		        filterChainDefinitionMap.put("/**", "jwt");
		        
		        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
		        // ========== 2. 动态加载权限核心部分结束 ==========
				
				// 3. 重新构建生成
				Map<String, String> chains = shiroFilterFactoryBean.getFilterChainDefinitionMap();
				for (Map.Entry<String, String> entry : chains.entrySet()) {
					String url = entry.getKey();
					String chainDefinition = entry.getValue().trim().replace(" ", "");
					manager.createChain(url, chainDefinition);
				}
				flag = true;
				System.out.println("更新权限成功");
			} catch (Exception e) {
				throw new RuntimeException("更新shiro权限出现错误!");
			}
		}
		return flag;
	}
}
